package com.zheng.upms.server.controller.manage;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.CamelUnderlineConverter;
import com.zheng.common.validator.LengthValidator;
import com.zheng.upms.common.constant.UpmsResult;
import com.zheng.upms.common.constant.UpmsResultConstant;
import com.zheng.upms.dao.model.UpmsSystem;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.upms.rpc.api.UpmsSystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统controller
 * Created by shuzheng on 2016/12/18.
 */
@Controller
@Api(value = "系统管理", description = "系统管理")
@RequestMapping("/manage/system")
public class UpmsSystemController extends BaseController {

	private static Logger _log = LoggerFactory.getLogger(UpmsSystemController.class);

	@Autowired
	private UpmsSystemService upmsSystemService;

	@Autowired
	private UpmsApiService upmsApiService;

	@ApiOperation(value = "系统首页")
	@RequiresPermissions("upms:system:read")
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index() {
		return "/manage/system/index.jsp";
	}

	@ApiOperation(value = "系统列表")
	@RequiresPermissions("upms:system:read")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public Object list(
			@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
			@RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
			@RequestParam(required = false, defaultValue = "", value = "searchText") String searchText,
			@RequestParam(required = false, value = "sortName") String sortName,
			@RequestParam(required = false, value = "sortOrder") String sortOrder) {
		Wrapper<UpmsSystem> wrapper = new EntityWrapper<>();
		if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
			if(sortOrder.equalsIgnoreCase("asc")){
				wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), true);
			}else {
				wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), false);
			}
		}
		if (StringUtils.isNotBlank(searchText)) {
			wrapper.like("title", searchText);
		}

		Page<UpmsSystem> page = upmsSystemService.selectPage(new Page<UpmsSystem>(pageNumber, pageSize), wrapper);
		long total = upmsSystemService.selectCount(wrapper);
		Map<String, Object> result = new HashMap<>();
		result.put("rows", page.getRecords());
		result.put("total", total);
		return result;
	}

	@ApiOperation(value = "新增系统")
	@RequiresPermissions("upms:system:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create() {
		return "/manage/system/create.jsp";
	}

	@ApiOperation(value = "新增系统")
	@RequiresPermissions("upms:system:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@ResponseBody
	public Object create(UpmsSystem upmsSystem) {
		ComplexResult result = FluentValidator.checkAll()
				.on(upmsSystem.getTitle(), new LengthValidator(1, 20, "标题"))
				.on(upmsSystem.getName(), new LengthValidator(1, 20, "名称"))
				.doValidate()
				.result(ResultCollectors.toComplex());
		if (!result.isSuccess()) {
			return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
		}
		Date date = new Date();
		upmsSystem.setCtime(date);
		if(upmsSystem.getOrders() == null) {
			upmsSystem.setOrders(System.currentTimeMillis());
		}
		Boolean isSuccess = upmsSystemService.insert(upmsSystem);
		if (!isSuccess) {
			return new UpmsResult(UpmsResultConstant.FAILED, isSuccess);
		}
		return new UpmsResult(UpmsResultConstant.SUCCESS, isSuccess);
	}

	@ApiOperation(value = "删除系统")
	@RequiresPermissions("upms:system:delete")
	@RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET)
	@ResponseBody
	public Object delete(@PathVariable("ids") String ids) {
		Boolean isSuccess = upmsSystemService.deleteBatchIds(ids);
		//清除缓存信息
		upmsApiService.evictUpmsServiceCache();
		if (!isSuccess) {
			return new UpmsResult(UpmsResultConstant.FAILED, isSuccess);
		}
		return new UpmsResult(UpmsResultConstant.SUCCESS, isSuccess);
	}

	@ApiOperation(value = "修改系统")
	@RequiresPermissions("upms:system:update")
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable("id") int id, ModelMap modelMap) {
		UpmsSystem system = upmsSystemService.selectById(id);
		modelMap.put("system", system);
		return "/manage/system/update.jsp";
	}

	@ApiOperation(value = "修改系统")
	@RequiresPermissions("upms:system:update")
	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	@ResponseBody
	public Object update(@PathVariable("id") int id, UpmsSystem upmsSystem) {
		ComplexResult result = FluentValidator.checkAll()
				.on(upmsSystem.getTitle(), new LengthValidator(1, 20, "标题"))
				.on(upmsSystem.getName(), new LengthValidator(1, 20, "名称"))
				.doValidate()
				.result(ResultCollectors.toComplex());
		if (!result.isSuccess()) {
			return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
		}
		upmsSystem.setSystemId(id);
		Boolean isSuccess = upmsSystemService.updateById(upmsSystem);
		//清除缓存信息
		upmsApiService.evictUpmsServiceCache();
		if(!isSuccess){
			return new UpmsResult(UpmsResultConstant.FAILED, isSuccess);
		}
		return new UpmsResult(UpmsResultConstant.SUCCESS, isSuccess);
	}

}